package com.crt.uav.rabbitmq.consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.crt.uav.config.UavMqProperties;

@Component
public class UavJMRabbitMqConsumer {

    @Autowired(required = false)
    @Qualifier("uavMessageListenerFactory")
    private UavMessageListenerFactory uavMessageListenerFactory;

    // @Autowired
    // private Map<String, CachingConnectionFactory> jmConnectionFactory;

    @Autowired(required = false)
    @Qualifier("connectionFactory")
    private CachingConnectionFactory connectionFactory;

    @Autowired(required = false)
    @Qualifier("thRabbitMqProperties")
    private UavMqProperties thRabbitMqProperties;

    private static Logger logger = LoggerFactory.getLogger(UavJMRabbitMqConsumer.class);

    /**
     * 启动 RabbitMQ 消息监听器
     */
    public void startJmRabbitMqListeners() {

        thRabbitMqProperties.getQueues().forEach(queue -> {
            String queueName = queue.get("queue");
            // 创建消息监听容器
            DirectMessageListenerContainer container = new DirectMessageListenerContainer(connectionFactory);
            container.setQueueNames(queueName);
            container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
            container.setMessageListener(uavMessageListenerFactory.getListener(queueName));
            container.start();
        });
        logger.info("RabbitMQ 消息监听器启动成功");
    }

}
